// backend/src/config/logger.js
import path from "path";
import fs from "fs";
import yaml from "js-yaml";
import log4js from 'log4js';
import {fileURLToPath} from 'url';

// 获取当前文件的目录名
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 读取配置文件
const config = yaml.load(fs.readFileSync(path.join(__dirname, '../application.yaml'), 'utf8'));

const logDirectory = path.join(__dirname, '../output/logs');
const logFilePath = path.join(logDirectory, 'info.log');
const errorLogFilePath = path.join(logDirectory, 'error.log');

// 确保日志目录存在
if (!fs.existsSync(logDirectory)) {
    fs.mkdirSync(logDirectory, {recursive: true});
}

// 配置 log4js
log4js.configure({
    appenders: {
        out: {type: 'stdout'},
        file: {
            type: 'file',
            filename: logFilePath,
            maxLogSize: typeof config.logging.file.maxSize === 'string'
                ? parseInt(config.logging.file.maxSize) * (config.logging.file.maxSize.includes('MB') ? 1048576 : 1)
                : config.logging.file.maxSize,
            backups: config.logging.file.maxFiles || 5,
            compress: config.logging.file.compress || true,
            encoding: 'utf-8'
        },
        errorFile: {
            type: 'file',
            filename: errorLogFilePath,
            maxLogSize: typeof config.logging.file.maxSize === 'string'
                ? parseInt(config.logging.file.maxSize) * (config.logging.file.maxSize.includes('MB') ? 1048576 : 1)
                : config.logging.file.maxSize,
            backups: config.logging.file.maxFiles || 5,
            compress: config.logging.file.compress || true,
            encoding: 'utf-8'
        }
    },
    categories: {
        default: {appenders: ['out', 'file'], level: config.logging.level || 'info'},
        error: {appenders: ['errorFile'], level: 'error'},
        http: {appenders: ['out', 'file'], level: 'info'}
    },
    disableClustering: true
});


// 创建日志记录器
const logger = log4js.getLogger();
const errorLogger = log4js.getLogger('error');
const httpLogger = log4js.getLogger('http');

export {logger, errorLogger, httpLogger};
